<?php

namespace App\Http\Controllers\Customer;

use App\Exceptions\AppException;
use App\Http\Controllers\Controller;
use App\Kit\Token;
use App\Models\CustomerModel;
use App\Models\SmsModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Sms\V20210111\SmsClient;

class Index extends Controller
{

    //注册
    public function register(Request $request){
        $params = $request->all();
        $validator = Validator::make($params, [
            'name' => 'required',
            'phone' => 'required',
//            'code' => 'required',
            'password' => 'required',

            'contact_person' => 'required',
            'email' => 'required',
            'contact_phone' => 'required',
            'contract' => 'required',
//            'province_id' => 'required',
//            'city_id' => 'required',
//            'addr' => 'required',

        ], [
            'name.required' => '名称不能为空',
            'phone.required' => '手机号不能为空',
//            'code.required' => '验证码不能为空',
            'password.required' => '密码不能为空',

            'contact_person.required' => '联系人不能为空',
            'email.required' => '邮箱不能为空',
            'contact_phone.required' => '联系电话不能为空',
            'contract.required' => '请上传开户合同',
//            'province_id.required' => '省份不能为空',
//            'city_id.required' => '城市不能为空',
//            'addr.required' => '地址不能为空',
        ]);
    
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $cusotmer = new CustomerModel();
        $cusotmer->account_status = CustomerModel::BLOCK_ACCOUNT;
        $cusotmer->review_status = 1; //待审核
        $cusotmer->name = $params['name'];
        $cusotmer->password = password_hash($params['password'], PASSWORD_DEFAULT);
        $cusotmer->contact_person = $params['contact_person'];
        $cusotmer->email = $params['email'];
        $cusotmer->contact_phone = $params['contact_phone'];
        $cusotmer->contract = $params['contract'];
        $cusotmer->province_id = $params['province_id'] ?? 0;
        $cusotmer->city_id = $params['city_id'] ?? 0;
        $cusotmer->addr = $params['addr'] ?? '';
        $cusotmer->account = $params['phone'];
        $cusotmer->remark = $params['remark'] ?? '';
        $cusotmer->wechat = $params['wechat'] ?? '';
        $cusotmer->created_admin_id = 0;
        $cusotmer->save();
        $cusotmer->sn = 'EML' . $cusotmer->id;
        $cusotmer->save();

        return $this->success('注册成功');

    }

    /**
     * Notes:注册验证码
     * User: xiangzi
     * Date: 2025/5/6
     * Time: 下午6:56
     * @return \Illuminate\Http\JsonResponse
     */
    public function check_code(Request $request){
        $params = $request->all();
        $validator = Validator::make($params, [
            'mobile' => 'required',
            'code' => 'required',
        ], [
            'mobile.required' => '手机号不能为空',
            'code.required' => '验证码不能为空',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }


        //检查验证码
        $find_code = SmsModel::where('mobile',$params['mobile'])
            ->where('code',$params['code'])
            ->where('time','>',time())
            ->where('is_used' ,0)
            ->first();
        if(!$find_code){
            return $this->error('验证码错误或已过期');
        }else{
            $find_code->is_used = 1;
            $find_code->save();
        }

        return $this->success();
    }

    //密码登录
    public function login_password(Request $request){
        $params = $request->all();
        $validator = Validator::make($params, [
            'account' => 'required',
            'password' => 'required',
        ], [
            'account.required' => '账号不能为空',
            'password.required' => '密码不能为空',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $cusotmer = CustomerModel::where('account',$params['account'])->first();
        if(!$cusotmer){
            return $this->error('账号不存在');
        }

        if($cusotmer->account_status == CustomerModel::BLOCK_ACCOUNT){
            return $this->error('账号已被禁用');
        }

        if($cusotmer->review_status != CustomerModel::REVIEW_PASSED){
            return $this->error('账号还未审核通过');
        }

        if(!password_verify($params['password'],$cusotmer->password)){
            return $this->error('密码错误');
        }

        $effective_time = 86400;
        $token = Token::get_csutomer_token($cusotmer->id);
        if(!$token) {
            $auth_info = [
                'id' => $cusotmer->id,
                'name' => $cusotmer->name,
                'sn' => $cusotmer->sn,
                'review_status' => $cusotmer->review_status,
                'account_status' => $cusotmer->account_status,
                'avatar' => $cusotmer->avatar,
            ];
            $token = Token::createToken($auth_info, $cusotmer->id, 'admin', $effective_time);
            Token::set_customer_token($token, $cusotmer->id, $effective_time);
        }

        return $this->success(["token" => $token]);
    }

    //验证码登录
    public function login_code(Request $request){
        $params = $request->all();
        $validator = Validator::make($params, [
            'account' => 'required',
            'code' => 'required',
        ], [
            'account.required' => '账号不能为空',
            'code.required' => '验证码不能为空',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $cusotmer = CustomerModel::where('account',$params['account'])->first();
        if(!$cusotmer){
            return $this->error('账号不存在');
        }

        if($cusotmer->account_status == CustomerModel::BLOCK_ACCOUNT){
            return $this->error('账号已被禁用');
        }

        if($cusotmer->review_status != CustomerModel::REVIEW_PASSED){
            return $this->error('账号还未审核通过');
        }

        //检查验证码
        $find_code = SmsModel::where('mobile',$params['account'])
            ->where('code',$params['code'])
            ->where('time','>',time())
            ->where('is_used' ,0)
            ->first();
        if(!$find_code){
            return $this->error('验证码错误或已过期');
        }else{
            $find_code->is_used = 1;
            $find_code->save();
        }

        $effective_time = 86400;
        $token = Token::get_csutomer_token($cusotmer->id);
        if(!$token) {
            $auth_info = [
                'id' => $cusotmer->id,
                'name' => $cusotmer->name,
                'sn' => $cusotmer->sn,
                'review_status' => $cusotmer->review_status,
                'account_status' => $cusotmer->account_status,
                'avatar' => $cusotmer->avatar,
            ];
            $token = Token::createToken($auth_info, $cusotmer->id, 'admin', $effective_time);
            Token::set_customer_token($token, $cusotmer->id, $effective_time);
        }

        return $this->success(["token" => $token]);

    }

    /**
     * Notes:账号信息
     * User: xiangzi
     * Date: 2025/4/29
     * Time: 上午10:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(Request $request){
        $auth = $request->get('auth');
        $data = [
            'id' => $auth->id,
            'name' => $auth->name,
            'sn' => $auth->sn,
            'avatar' => $auth->avatar,
        ];
        return $this->success($data);
    }

    //上传
    public function upload(Request $request)
    {
        // 验证请求中的文件
        $validator = Validator::make($request->all(), [
            'file' => 'required|file',
        ], [
            'file.required' => '请上传文件',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        // 获取上传的文件
        $file = $request->file('file');

        // 获取原始文件名
        $originalFileName = $file->getClientOriginalName();
        $fileNameWithoutExtension = pathinfo($originalFileName, PATHINFO_FILENAME);

        // 读取文件内容并计算 MD5 哈希值
        $fileContent = file_get_contents($file->getPathname());
//        $md5FileName = md5($fileContent) . '.' . $file->getClientOriginalExtension();


        // 定义保存路径
        $upload_path = 'uploads/files/'. date('Ymd');
        $destinationPath = public_path($upload_path);

        // 确保目录存在
        if (!file_exists($destinationPath)) {
            mkdir($destinationPath, 0755, true);
        }

        // 返回保存的文件路径
        $filePath = $upload_path.'/'.$originalFileName;

        //如果文件存在
        if(file_exists($destinationPath.'/'.$originalFileName)) {
            $originalFileName = $fileNameWithoutExtension . '_' . date('YmdHis') . '.' . $file->getClientOriginalExtension();
            $filePath = $upload_path.'/'.$originalFileName;
        }

        // 移动文件到目标路径
        $file->move($destinationPath, $originalFileName);

        return $this->success(['path' => $filePath]);
    }

    public function sendSms(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = mt_rand(1000,9999);
        $sms_content="验证码为:{$code}，若非本人操作，请勿泄露。";
        $templateId = config("sms.templateId");
        $send = $this->tencentSendSms($mobile,$templateId,$code,$sms_content);
        $return = json_decode($send,true);

        $model = new SmsModel();
        $model->mobile = $mobile;
        $model->code = $code;
        $model->content = $sms_content;
        $model->ip = $request->ip();
        $model->time = time() + 120;
        $model->return = current($return['SendStatusSet'])['Message'];
        $model->log = $send;
        $model->save();

        if(current($return['SendStatusSet'])['Code'] == 'Ok'){
            return $this->success();
        }else{
            return $this->error('短信发送失败');
        }
    }


    public function tencentSendSms($phone, $template, $code, $sms_content = '')
    {
        try {
            /* 必要步骤：
               * 实例化一个认证对象，入参需要传入腾讯云账户密钥对secretId，secretKey。
               * 这里采用的是从环境变量读取的方式，需要在环境变量中先设置这两个值。
               * 你也可以直接在代码中写死密钥对，但是小心不要将代码复制、上传或者分享给他人，
               * 以免泄露密钥对危及你的财产安全。
               * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/
            /********************************************1.secretId,secretKey***********************************************/
            $cred = new Credential(config("sms.secretId"), config("sms.secretKey"));

            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            // 配置代理
            // $httpProfile->setProxy("https://ip:port");
            $httpProfile->setReqMethod("GET");  // post请求(默认为post请求)
            $httpProfile->setReqTimeout(30);    // 请求超时时间，单位为秒(默认60秒)
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");  // 指定接入地域域名(默认就近接入)

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法(默认为HmacSHA256)
            $clientProfile->setHttpProfile($httpProfile);

            // 实例化要请求产品(以sms为例)的client对象,clientProfile是可选的
            // 第二个参数是地域信息，可以直接填写字符串 ap-guangzhou，或者引用预设的常量
            $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);

            // 实例化一个 sms 发送短信请求对象,每个接口都会对应一个request对象。
            $req = new SendSmsRequest();

            /* 填充请求参数,这里request对象的成员变量即对应接口的入参
             * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
             * 基本类型的设置:
             * 帮助链接：
             * 短信控制台: https://console.cloud.tencent.com/smsv2
             * sms helper: https://cloud.tencent.com/document/product/382/3773 */

            /************************ 2.短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
            $req->SmsSdkAppId = config("sms.sdkAppID");//"1400616870";
            /**************************3.短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名，签名信息可登录 [短信控制台] 查看 */
            $req->SignName = config("sms.smsSign");
            /* 短信码号扩展号: 默认未开通，如需开通请联系 [sms helper] */
            $req->ExtendCode = "";
            /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
             * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
            /**************************4.手机号*****************************/
            if(is_array($phone)){
                $req->PhoneNumberSet = $phone;
            }else{
                $req->PhoneNumberSet = array($phone);
            }

            /* 国际/港澳台短信 SenderId: 国内短信填空，默认未开通，如需开通请联系 [sms helper] */
            $req->SenderId = "";
            /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
            $req->SessionContext = $sms_content;
            /****************************5.模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */
            $req->TemplateId = $template;
            /****************************6.模板变量 模板参数: 若无模板参数，则设置为空*/
            $req->TemplateParamSet = array($code);

            // 通过client对象调用SendSms方法发起请求。注意请求方法名与请求对象是对应的
            // 返回的resp是一个SendSmsResponse类的实例，与请求对象对应
            $resp = $client->SendSms($req);
            // 输出json格式的字符串回包
            return $resp->toJsonString();
        }
        catch(TencentCloudSDKException $e) {
            throw new AppException($e->getMessage());
        }

    }

}
